package com.example.alpha.campusbase.Fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.example.alpha.campusbase.R;

public class FeedbackFragment extends Fragment {

    private InputMethodManager mInput;
    private FeedTask mAuthTask=null;
    private View mFeedViewForm;
    private View mProgessView;
    private EditText mFeedMessageView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View feedview=inflater.inflate(R.layout.feedback_layout,container,false);
        mFeedMessageView= (EditText) feedview.findViewById(R.id.feed_message_input);
        final Button mCommitButtom= (Button) feedview.findViewById(R.id.feed_commit_button);
        mCommitButtom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取输入法管理器
                mInput= (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                verifyMessage();
            }
        });

        mFeedViewForm=feedview.findViewById(R.id.feedback_form);
        mProgessView=feedview.findViewById(R.id.feedback_progress);
        return feedview;
    }

    //验证反馈信息的合法性
    private void verifyMessage(){
        if (mAuthTask!=null){
            return;
        }
        mFeedMessageView.setError(null);
        Boolean mCancle=false;
        View focusView=null;
        showProgress(false);
        if(TextUtils.isEmpty(mFeedMessageView.getText())){
            mFeedMessageView.setError(getResources().getString(R.string.error_field_required));
            focusView=mFeedMessageView;
            mCancle=true;
        }
        else if (mFeedMessageView.getText().length()<20){
            mFeedMessageView.setError(getResources().getString(R.string.not_enougn_long));
            focusView=mFeedMessageView;
            mCancle=true;
        }

        if (mCancle){
            focusView.requestFocus();
        }
        else {
            showProgress(true);
            mAuthTask=new FeedTask(mFeedMessageView.getText().toString());
            mAuthTask.execute((Void) null);
        }
    }

    /**
     * 显示进度条并隐藏登陆界面
     * 或
     * 隐藏进度条并显示登陆界面
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // 判断是否可以进行动画
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mFeedViewForm.setVisibility(show ? View.GONE : View.VISIBLE);
            mFeedViewForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mFeedViewForm.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgessView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgessView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgessView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            mProgessView.setVisibility(show ? View.VISIBLE : View.GONE);
            mFeedViewForm.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    //异步请求任务，用于网络提交时显示进度条
    public class FeedTask extends AsyncTask<Void, Void, Boolean> {

        private final String mFeedMessage;

        //构造
        FeedTask(String message) {
            mFeedMessage = message;
        }

        //真正的账户信息校验
        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: 添加网络数据验证请求
            try {
                //模拟网络请求1秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                return false;
            }

            // TODO: 2016/6/9 网络验证结果，需更新；可改为其他验证结果
            return true;

        }

        //提交后的反馈步骤
        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                Snackbar.make(mFeedMessageView,getString(R.string.feedback_commit_success),
                        Snackbar.LENGTH_SHORT).show();
                //隐藏输入键盘
                mInput.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                mFeedMessageView.setError(getString(R.string.error_invalid_feedmessage));
                mFeedMessageView.requestFocus();
            }
            mFeedMessageView.setText("");
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

}
